package com.movie.controller;

// import com.movie.dto.OrderDTO; // DTO 可能也需要调整或移除
import com.movie.entity.Order;
import com.movie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
// import org.springframework.transaction.annotation.Transactional; // 移除
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.time.LocalDate;
import java.util.List;
import java.util.Map; // 添加 Map 导入
// import java.util.stream.Collectors; // 移除

@RestController
@RequestMapping("/api/orders")
// @CrossOrigin(origins = "http://localhost:5173") // 暂时移除
public class OrderController {

    @Autowired
    private OrderService orderService;

    // 创建订单
    @PostMapping
    public ResponseEntity<?> createOrder(@RequestBody Order order) {
        try {
            // 生成订单号
            String orderNumber = "ORD" + System.currentTimeMillis();
            order.setOrderNumber(orderNumber);

            // 设置订单状态为待支付
            order.setStatus(0);

            // 打印订单信息，用于调试
            System.out.println("Creating order: " + order);

            // 创建订单
            Order createdOrder = orderService.createOrder(order);
            return ResponseEntity.ok(createdOrder);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("创建订单失败: " + e.getMessage());
        }
    }

    // 保留: 获取用户订单
    @GetMapping("/user/{userId}")
    // 添加权限校验: 允许管理员或用户本人访问
    // 注意: authentication.principal 需要有 getId() 方法
    @PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.getId()")
    public ResponseEntity<List<Order>> getUserOrders(@PathVariable Long userId) {
        List<Order> orders = orderService.getOrdersByUserId(userId);
        return ResponseEntity.ok(orders);
    }

    // 保留: 获取特定订单详情
    @GetMapping("/{orderId}")
    public ResponseEntity<Order> getOrderDetails(@PathVariable Long orderId) {
        // 需要权限校验: 确保是订单所有者或管理员
        Order order = orderService.getOrderById(orderId);
        if (order != null) {
            return ResponseEntity.ok(order);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 保留: 取消订单
    @PutMapping("/{orderId}/cancel")
    public ResponseEntity<?> cancelOrder(@PathVariable Long orderId) {
        try {
            // 需要权限校验: 确保是订单所有者或管理员
            orderService.cancelOrder(orderId); // 直接调用 void 方法
            // 如果没有异常抛出，则认为操作成功
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "订单取消成功"
            ));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of(
                "success", false,
                "message", e.getMessage()
            ));
        }
        // Service层在无法取消时应抛出异常 (例如 ResourceNotFoundException)，
        // 这些异常通常由全局异常处理器处理并返回合适的HTTP状态码（如404或400）。
    }

    // 支付订单
    @PostMapping("/{orderId}/pay")
    public ResponseEntity<?> payOrder(@PathVariable Long orderId) {
        try {
            // 获取当前登录用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("message", "用户未登录"));
            }

            String username = authentication.getName();

            // 调用Service层处理支付
            Order paidOrder = orderService.payOrder(orderId, username);

            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "支付成功",
                "order", paidOrder
            ));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of(
                "success", false,
                "message", e.getMessage()
            ));
        }
    }

    // 批量支付订单
    @PostMapping("/batch-pay")
    public ResponseEntity<?> batchPayOrders(@RequestBody Map<String, List<Long>> request) {
        try {
            List<Long> orderIds = request.get("orderIds");
            if (orderIds == null || orderIds.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "订单ID列表不能为空"
                ));
            }

            // 获取当前登录用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("message", "用户未登录"));
            }

            String username = authentication.getName();

            // 调用Service层处理批量支付
            List<Order> paidOrders = orderService.batchPayOrders(orderIds, username);

            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "批量支付成功",
                "orders", paidOrders
            ));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of(
                "success", false,
                "message", e.getMessage()
            ));
        }
    }

    // 添加：管理员分页获取所有订单
    @GetMapping("/admin/paged")
    @PreAuthorize("hasRole('ADMIN')") // 确保只有管理员能访问
    public ResponseEntity<Map<String, Object>> getAllOrdersPaged(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Map<String, Object> result = orderService.getAllOrdersPaged(page, size);
        return ResponseEntity.ok(result);
    }

    // 移除 getAllOrders (接口中已定义 getAllOrders)
    // 移除 getOrdersPaged
    // 移除 getOrdersByUser (已用 getUserOrders 替代)
    // 移除 getOrdersByUserPaged
    // 移除 createOrder(Map...)
    // 移除 createOrderFromBook
    // 移除 updateOrderStatus
    // 移除 deleteOrder (Service 层未定义)
    // 移除 batchDeleteOrders

    // 添加批量取消订单接口
    @PostMapping("/batch-cancel")
    public ResponseEntity<?> batchCancelOrders(@RequestBody Map<String, List<Long>> request) {
        try {
            List<Long> orderIds = request.get("orderIds");
            if (orderIds == null || orderIds.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "订单ID列表不能为空"
                ));
            }

            // 获取当前登录用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of(
                    "success", false,
                    "message", "用户未登录"
                ));
            }

            // 逐个取消订单
            for (Long orderId : orderIds) {
                try {
                    orderService.cancelOrder(orderId);
                } catch (Exception e) {
                    // 记录错误但继续处理其他订单
                    System.err.println("取消订单 " + orderId + " 失败: " + e.getMessage());
                }
            }

            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "批量取消订单成功"
            ));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of(
                "success", false,
                "message", e.getMessage()
            ));
        }
    }

    // 如果需要管理员获取所有订单的功能，可以添加一个新端点
    // @GetMapping("/admin/all")
    // public ResponseEntity<List<Order>> getAllOrdersAdmin() {
    //     // 需要管理员权限校验
    //     List<Order> orders = orderService.getAllOrders();
    //     return ResponseEntity.ok(orders);
    // }

}

